﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Repository;
using LeadVinaglue.Models;
using LeadVinaglue.Helpers;
using LeadVinaglue.Utility;

namespace LeadVinaglue.Areas.MyAccount.Controllers
{
    public class ProductListController : Controller
    {
        // Create an instance of user manage
        LeadVinaglue.Repository.ProductManagementRepository repository = new LeadVinaglue.Repository.ProductManagementRepository();
        public static string ProductImagesURL = ConfigurationManager.AppSettings["ProductImagesURL"].ToString();
        public static string ProductAttachURL = ConfigurationManager.AppSettings["ProductAttachURL"].ToString();


        // GET: /Management/Home/
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Index()
        {
            // Get User ID
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            model = repository.GetModelByUser(user.ID, "Menu", "ClientAdmin", 10, 1);

            return View(model);
        }


        [HttpPost]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Fillter(string keywords, string startDate, string endDate, string categoryId, int pageSize, int pageIndex, int id, string sortBy, string sortOrder)
        {
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            string[] categories = categoryId.Split(',');

            model = repository.GetModelByUser(user.ID, "Menu", "ClientAdmin", keywords, startDate, endDate, categories, sortBy, sortOrder, pageSize, pageIndex, id);

            return Json(model);
        }


        // GET: /Management/Product/Search?keywords=tt&fieldName=type
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Search(string keywords, string fieldName)
        {
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            model = repository.GetModelByUser(user.ID, Helpers.Constant.HOME, "ClientAdmin", keywords, fieldName, 10, 1);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult SearchFillter(string keywords, string fieldName, int pageSize, int pageIndex)
        {
            ProductManagementModel model = new ProductManagementModel();
            var userId = new Repository.UserRepository().GetSingle(User.Identity.Name).ID;
            model = repository.GetModelByUser(userId, Helpers.Constant.HOME, "ClientAdmin", keywords, fieldName, pageSize, pageIndex);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return Json(model);
        }

        // GET: /Management/Home/
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Add()
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.PRODUCT, "ClientAdmin", 0);

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Add(FormCollection form)
        {
            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            // Create product
            Product model = new Product();

            model.GUID = Guid.NewGuid().ToString();
            model.Title = form["Title"].ToString();
            model.LongDesc = form["LongDesc"].ToString();
            model.ImageURL = form["ImageUrl"].ToString();
            model.FileName = form["FileName"].ToString();
            model.FileType = form["FileType"].ToString();
            model.CategoryID = (form["CategoryID"] != null) ? int.Parse(form["CategoryID"].ToString()) : 0;
            model.SubCategoryID = (form["SubCategoryID"] != null) ? int.Parse(form["SubCategoryID"].ToString()) : 0;
            model.LanguageId = (form["LanguageId"] != null) ? int.Parse(form["LanguageId"].ToString()) : 0;
            model.DocumentTypeId = (form["TypeId"] != null) ? int.Parse(form["TypeId"].ToString()) : 0;
            model.CreatedByUserID = user.ID;
            model.IsPublic = (form["IsPublic"] != null && form["IsPublic"].ToString() == "on") ? true : false;
            model.Active = false;

            repository.Create(model);

            return Redirect("/MyAccount/ProductList");
        }

        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Edit(int id)
        {
            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);

            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel("Menu", "ClientAdmin", id);
            model.ProductImageUrl = ProductImagesURL;
            if (model.ProductInfo == null || model.ProductInfo.CreatedByUserID != user.ID)
                return Redirect("/MyAccount/ProductList");

            ViewBag.ProductId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Edit(int id, FormCollection form)
        {
            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            Product model = repository.GetSingle(id);
            Product modelNew = new Product();

            if (model == null || model.CreatedByUserID != user.ID)
                return Redirect("/MyAccount/ProductList");

            model.Title = form["Title"].ToString();
            model.LongDesc = form["LongDesc"].ToString();
            model.ImageURL = form["ImageUrl"].ToString();
            model.FileName = form["FileName"].ToString();
            model.FileType = form["FileType"].ToString();
            model.CategoryID = (form["CategoryID"] != null) ? int.Parse(form["CategoryID"].ToString()) : 0;
            model.SubCategoryID = (form["SubCategoryID"] != null) ? int.Parse(form["SubCategoryID"].ToString()) : 0;
            model.LanguageId = (form["LanguageId"] != null) ? int.Parse(form["LanguageId"].ToString()) : 0;
            model.DocumentTypeId = (form["TypeId"] != null) ? int.Parse(form["TypeId"].ToString()) : 0;
            model.IsPublic = (form["IsPublic"] != null && form["IsPublic"].ToString() == "on") ? true : false;

            repository.Update(model);

            return Redirect("/MyAccount/ProductList");
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);
                string originalFileName = Path.GetFileName(fileData.FileName);
                string prefix = new Random().Next(1000000, 9999999).ToString();
                string guid = Guid.NewGuid().ToString();

                // clear special chars
                fileName = string.Format("{0}{1}", StringClearFormat.ClearSpecials(fileName.Substring(0, fileName.Length - 4)), fileName.Substring(fileName.Length - 4, 4));

                originalFileName = string.Format("{0}-{1}", prefix, fileName);
                fileName = string.Format("{0}-{1}", guid, fileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(ProductImagesURL), originalFileName);
                fileData.SaveAs(path);

                model.FileName = originalFileName;
                model.FilePath = string.Format("{0}/{1}", ProductImagesURL, originalFileName);
            }

            // redirect back to the index action to show the form once again
            return Json(model);
        }


        [HttpPost]
        public ActionResult UploadAttach(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty, fileExt = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);
                fileExt = Path.GetExtension(fileData.FileName);

                string originalFileName = Path.GetFileName(fileData.FileName);
                string prefix = new Random().Next(1000000, 9999999).ToString();
                string guid = Guid.NewGuid().ToString();

                // clear special chars
                fileName = string.Format("{0}{1}", StringClearFormat.ClearSpecials(fileName.Replace(fileExt, string.Empty)), fileExt);

                originalFileName = string.Format("{0}-{1}", prefix, fileName);
                fileName = string.Format("{0}-{1}", guid, fileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(ProductAttachURL), originalFileName);
                fileData.SaveAs(path);

                model.OriginalAttachName = fileData.FileName;
                model.AttachName = originalFileName;
                model.AttachType = fileExt;
                //model.ImageUrl = string.Format("{0}/{1}", ProductAttachURL, originalFileName);

            }

            // redirect back to the index action to show the form once again
            return Json(model);
        }
    }
}
